package lesson3.models;

import components.CircleCollider;
import components.HP;
import components.RotateTowardsMouse;
import java2d.game.GameObject;
import java2d.game.Inputs;
import java2d.game.Maths;
import java2d.game.Time;
import utils.PlayerInputs;

import java.awt.*;
import java.awt.geom.Point2D;

/**
 * Author:     Zhao Yan
 * DateTime:   2023/4/18 18:48
 */
public class Player extends Spacecraft implements CircleCollider.CollideEnterEvent {

    public double speed = 5d;

    public final RotateTowardsMouse rotateTowardsMouse = new RotateTowardsMouse();

    public boolean canMove = true;

    public Player() {
        super("assets/sprites/spacecraft.png");
        name = "Player";
        tag = "Player";
        targetTag = "Enemy";
        transform.setLocalScale(2, 2);
        transform.setPosition(0, 280);

        shootDirection.setLocation(0, -1.0);
        hpBar.transform.setLocalPosition(0, 20);

        collider.collideEnterEvent = this;
        collider.radius = 10;

        rotateTowardsMouse.visible = false;
        rotateTowardsMouse.stringRender.visible = false;
        addComponent(rotateTowardsMouse);
    }

    @Override
    protected void onUpdate() {
        if (isDestroyed())
            return;

        // 1、使用 World Mouse Position 来减去当前飞船 Position，得到一个方向向量
//        Point2D dir = Maths.subtract(getInputs().getWorldMousePosition(), transform.getPosition());

        // 2、使用当前飞船本身的旋转方向，加上一个修正量来作为最终的射击方向
        Point2D dir = Maths.toDirection(transform.getLocalRotation() - 90);
        Maths.normalize(dir);
        shootDirection.setLocation(dir);

        updateIntervalShoot();

        if (isDestroyed() || !canMove)
            return;

        Point2D direction = new Point2D.Double();
        Inputs inputs = getInputs();
        PlayerInputs.setAxes(inputs, direction);
        direction.setLocation(direction.getX(), 0);
        transform.translate(Maths.multiple(direction,
                speed * Time.deltaTime * 100));
    }

    @Override
    protected void setupBullet(Bullet bullet) {
        bullet.damage = 20;
        Point2D worldMousePosition = getInputs().getWorldMousePosition();
        Point2D pos = transform.getPosition();

        bullet.translator.maxDistance =
                Point2D.distance(worldMousePosition.getX(), worldMousePosition.getY(),
                        pos.getX(), pos.getY());

        bullet.translator.reachMaxDistance = b -> b.getGameObject().destroy();
    }

    @Override
    public void collideEnter(CircleCollider other) {
        GameObject target = other.getGameObject();

        if (target.compareTag("Enemy")) {
            hp.setValue(hp.getValue() - target.getComponent(HP.class).getValue());
            target.destroy();
        }
    }
}
